package com.haltakov.letterjumble.ui.components;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.Border;

import com.haltakov.letterjumble.Messages;
import com.haltakov.letterjumble.game.api.BoardWord;
import com.haltakov.letterjumble.game.api.Player;

import static com.haltakov.letterjumble.ui.LookAndFeel.PANEL_BORDER_COLOR;

public class PlayerPanel extends JPanel {
	
	private static final long serialVersionUID = 1L;
	
	private Player player;
	private JLabel nameLabel;
	private JLabel playerTypeLabel;
	private JLabel scoreLabel;
	private JTextArea wordList;
	
	public PlayerPanel() {
		super(new BorderLayout(20, 20));
		
		setVisible(false);
		
		setBackground(PANEL_BORDER_COLOR);
		
		Border inner = BorderFactory.createEmptyBorder(5, 5, 5, 5);
		Border outer = BorderFactory.createRaisedBevelBorder();
		setBorder(BorderFactory.createCompoundBorder(outer, inner));
		
		wordList = new JTextArea();
		wordList.setBorder(BorderFactory.createLoweredBevelBorder());
		add(wordList, BorderLayout.CENTER);

		Font normalFont = new Font(Font.SANS_SERIF, Font.PLAIN, 12);
		Font boldFont = new Font(Font.SANS_SERIF, Font.BOLD, 12);
		
		JPanel topPanel = new JPanel(new GridLayout(2, 2, 10, 10));
		topPanel.setOpaque(false);
		add(topPanel, BorderLayout.NORTH);
		
		nameLabel = new JLabel("NAME%"); //$NON-NLS-1$
		nameLabel.setFont(boldFont);
		topPanel.add(nameLabel);
		 
		playerTypeLabel = new JLabel("TYPE"); //$NON-NLS-1$
		playerTypeLabel.setFont(normalFont);
		topPanel.add(playerTypeLabel);
		 
		JLabel scoreNameLabel = new JLabel(Messages.getString("PlayerPanel.scores")); //$NON-NLS-1$
		scoreNameLabel.setFont(boldFont);
		topPanel.add(scoreNameLabel);
		 
		scoreLabel = new JLabel("15"); //$NON-NLS-1$
		scoreLabel.setFont(normalFont);
		topPanel.add(scoreLabel);
	}
	
	public void update() {
		scoreLabel.setText("" + player.getScore()); //$NON-NLS-1$
		
		StringBuilder words = new StringBuilder();
		
		for (BoardWord word: player.getWordsHistory()) {
			words.append(word.toString() + "\n"); //$NON-NLS-1$
		}
		
		wordList.setText(words.toString());		
	}
	
	public void setPlayer(Player player) {
		if (player == null) {
			setVisible(false);
			return;
		}
		
		this.player = player;
		
		nameLabel.setText(player.getName());
		
		switch (player.getType()) {
		case HUMAN: playerTypeLabel.setText(Messages.getString("PlayerPanel.human")); break; //$NON-NLS-1$
		case COMPUTER: playerTypeLabel.setText(Messages.getString("PlayerPanel.computer")); break; //$NON-NLS-1$
		}
		
		scoreLabel.setText("" + player.getScore()); //$NON-NLS-1$
		
		setVisible(true);
	}
}
